import { session } from "@ui/utils/temp"
import { TabPaneName } from "element-plus"
import { menu, getMenu, menuList } from './getMenu'
export function use() {
  const route = useRoute(),
    router = useRouter(),
    selectMenuProp: { [key: string]: UserMenuPropName } = {
      children: 'page',
      label: 'pageName'
    },
    title = ref<string>('医院管理信息系统'),
    selectId = ref<string>(session('user-menu-selectId') || ''),
    menuTabList = ref<UserMenu[]>(session('user-menu-tab') || []),
    selectItem = computed(() => {
      const pageId = selectId.value
      return pageId ? menuList.value.filter(it => it.pageId == pageId)[0] : undefined
    }),
    currentPath = route.path,
    pro = getMenu()
  // 通过route路劲获取首次进入页面的pageId
  onMounted(() => {
    pro.then(() => {
      menuList.value.forEach((it) => {
        const { pageUrl, pageId } = it
        if ('/home/' + pageUrl === currentPath) {
          const judge = menuTabList.value.filter(it => it.pageId === pageId)[0]
          selectId.value = pageId
          if (!judge) {
            selectMenu(pageId)
          }
        }
      })
    })
  })
  // 监听selectId变化更改路由
  watch(() => selectItem.value, (v) => {
    if (v) {
      const path = v.pageUrl
      session('user-menu-selectId', v.pageId)
      router.push(`/home/${path}`);
    }
  }, { immediate: true })
  function selectMenu(pageId: string) {
    const menuTab = menuTabList.value, judge = menuTab.filter(it => it.pageId === pageId)[0]
    if (!judge && selectItem.value) {
      menuTab.push(selectItem.value)
      session('user-menu-tab', menuTabList.value)
    }
  }
  function tabRemove(pageId: TabPaneName): any {
    const menuTab = menuTabList.value
    if (menuTab.length < 2) {
      ElMessage({ type: 'warning', message: '最后一个不能删除' })
    } else {
      menuTabList.value = menuTab.filter(it => it.pageId !== pageId)
      if (selectId.value == pageId) {
        selectId.value = menuTabList.value[0].pageId
      }
      session('user-menu-tab', menuTabList.value)
    }
  }
  function cancelEvent() {

  }
  function exit() {

  }
  return {
    title,
    selectId,
    menu,
    selectMenu,
    selectMenuProp,
    menuTabList,
    tabRemove,
    cancelEvent,
    exit
  }
}